package com.unc.allergyex.adapters;

import java.util.ArrayList;


import com.unc.allergyex.R;
import com.unc.allergyex.objects.AllergyPreference;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * Adapter passed to setListAdapter in the onCreate method of {@link Preferences}.
 * Responsible for managing the layouts for each allergy in the list.
 * The layout of each list item is defined by layout/preferencesitem.xml.
 * 
 * @author Ryan Miller
 *
 */

public class AllergyPreferenceAdapter extends ArrayAdapter<AllergyPreference>{

	private ArrayList<AllergyPreference> preferences;
	
	/**
	 * Creates a new list adapter.
	 * 
	 * @param context the context of the Activity this object is constructed in
	 * @param textViewResourceId resource id of the layout used for each list item
	 * @param items an ArrayList of AllergyPreference objects that contains the name and allergic information for each allergy.
	 */

	public AllergyPreferenceAdapter(Context context, int textViewResourceId,
			ArrayList<AllergyPreference> items) {
		super(context, textViewResourceId, items);
		preferences = items;
	}
	
	/**
	 * Method called whenever a list item view is drawn on the screen.
	 * The standard documentation for this method is provided in {@link http://www.androidjavadoc.com/1.0_r1/android/widget/ArrayAdapter.html}.
	 */
	
	public View getView(int position, View convertView, ViewGroup parent) {
		View v;

		LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
		v = vi.inflate(R.layout.preferencesitem, null);

		AllergyPreference p = preferences.get(position);
		if (p != null) {
			
			TextView allergyName = (TextView) v.findViewById(R.id.allergyName);
			TextView number = (TextView) v.findViewById(R.id.position);
			CheckBox allergic = (CheckBox) v.findViewById(R.id.checkBox);
			RelativeLayout background = (RelativeLayout) v.findViewById(R.id.preferencesItem);
			

			if(number != null){
				number.setText(Integer.toString(position));
			}
			
			if(allergyName != null){
				allergyName.setText(p.getAllergen().getName());
			}
			
			if(allergic != null){
				if(p.getAllergic()){
					allergic.setChecked(true);
					background.setBackgroundColor(0xFFA50030);
					allergyName.setTextColor(0xFFFFFFFF);
				}
			}
			
		}
		return v;
	}
}
